package org.jeecg.modules.feature;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.dataSet.entity.DataSet;
import org.jeecg.modules.dataSet.service.IDataSetService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.dataSlot.entity.DataSlot;
import org.jeecg.modules.feature.vo.PredictParam;
import org.jeecg.modules.userFormula.entity.UserFormulaDetail;
import org.jeecg.modules.util.HttpClientUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 数据集
 * @Date: 2023-05-31
 */
@Api(tags = "数据集")
@RestController
@RequestMapping("/feature")
@Slf4j
public class FeatureController extends JeecgController<DataSet, IDataSetService> {
    @Value("${zf-jqxx-service.url}")
    private String zfserviceUrl;

    /**
     * 分页列表查询
     */
    //@AutoLog(value = "数据集-分页列表查询")
    @ApiOperation(value = "数据集-分页列表查询", notes = "数据集-分页列表查询")
    @GetMapping(value = "/rawData")
    public Result<IPage<Object>> rawData(@RequestParam(name = "slotNo", required = true) String slotNo,
                                         @RequestParam(name = "startDate", required = true) String startDate,
                                         @RequestParam(name = "endDate", required = true) String endDate,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        // QueryWrapper<DataSet> queryWrapper = QueryGenerator.initQueryWrapper(dataSet, req.getParameterMap());
        // Page<DataSet> page = new Page<DataSet>(pageNo, pageSize);
        //IPage<DataSet> pageList = dataSetService.page(page, queryWrapper);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("slot_no", slotNo);
        paramsMap.put("begin_date", startDate);
        paramsMap.put("end_date", endDate);
        paramsMap.put("page_size", pageSize.toString());
        paramsMap.put("page_number", pageNo.toString());
        IPage<Object> pageList = new Page<Object>();
        try {
            String url = zfserviceUrl + "/feature/raw_data";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object == null) {
                return Result.error("查询失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                pageList.setRecords((List<Object>) object.get("data"));
                pageList.setTotal(Long.parseLong(object.get("length").toString()));
                pageList.setSize(pageSize);
                pageList.setCurrent(pageNo);
                return Result.OK(pageList);
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("查询失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("查询失败，请联系管理员");
        }
    }

    @ApiOperation(value = "数据集-提取特征值", notes = "数据集-提取特征值")
    @GetMapping(value = "/features")
    public Result<IPage<Object>> features(@RequestParam(name = "datasetName", required = true) String datasetName,
                                          @RequestParam(name = "timeInterval", required = true) String timeInterval,
                                          @RequestParam(name = "intervalUnit", required = true) String intervalUnit,
                                          @RequestParam(name = "selectMethod", required = true) String selectMethod,
                                          HttpServletRequest req) {
        // QueryWrapper<DataSet> queryWrapper = QueryGenerator.initQueryWrapper(dataSet, req.getParameterMap());
        // Page<DataSet> page = new Page<DataSet>(pageNo, pageSize);
        //IPage<DataSet> pageList = dataSetService.page(page, queryWrapper);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("dataset_name", datasetName);
        paramsMap.put("time_interval", timeInterval);
        paramsMap.put("interval_unit", intervalUnit);
        paramsMap.put("select_method", selectMethod);
        IPage<Object> pageList = new Page<Object>();
        try {
            String url = zfserviceUrl + "/ds/ds_feature";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object == null) {
                return Result.error("查询失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                pageList.setRecords((List<Object>) object.get("data"));
                pageList.setTotal(Long.parseLong(object.get("length").toString()));
                pageList.setSize(999999);
                pageList.setCurrent(1);
                return Result.OK(pageList);
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("查询失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("查询失败，请联系管理员");
        }
    }

    @AutoLog(value = "数据预测-预测")
    @ApiOperation(value = "数据预测-预测", notes = "数据预测-预测")
    @PostMapping(value = "/predict")
    public Result<String> predict(@RequestBody PredictParam predictParam) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("dataset_name",predictParam.getDatasetCode());
        paramsMap.put("model_name", predictParam.getModelBaseCode());
        paramsMap.put("predict_property", predictParam.getPredictProperty());
        paramsMap.put("reset_columns",predictParam.getResetColumns());
        try {
            String url = zfserviceUrl + "/ml/predict";
            JSONObject object = HttpClientUtil.sendPost(url, paramsMap);
            if (object == null) {
                return Result.error("查询失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK(object.get("data").toString());
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("查询失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("查询失败，请联系管理员");
        }
    }
}
